import os
import sys
import argparse
import uvicorn
from uvicorn.config import LOGGING_CONFIG


def main():
    """主函数，支持命令行参数选择环境"""
    parser = argparse.ArgumentParser(description="Vue FastAPI Admin 启动脚本")
    parser.add_argument(
        "env", 
        nargs="?", 
        default="dev", 
        choices=["dev", "pro", "test"], 
        help="环境选择: dev(开发), pro(生产), test(测试) (默认: dev)"
    )
    parser.add_argument(
        "--host", 
        default="0.0.0.0", 
        help="服务器地址 (默认: 0.0.0.0)"
    )
    parser.add_argument(
        "--port", 
        type=int, 
        default=9999, 
        help="服务器端口 (默认: 9999)"
    )
    parser.add_argument(
        "--no-reload", 
        action="store_true", 
        help="关闭热重载"
    )
    
    args = parser.parse_args()
    
    # 设置环境变量
    os.environ["ENV"] = args.env
    
    print(f"🚀 启动 Vue FastAPI Admin - {args.env} 环境")
    print(f"📁 配置文件: env/.env.{args.env}")
    print(f"🌐 服务地址: http://{args.host}:{args.port}")
    # 确定是否启用热重载
    enable_reload = not args.no_reload and args.env != "pro"
    
    print(f"🔄 热重载: {'开启' if enable_reload else '关闭'}")
    print("-" * 50)
    
    # 修改默认日志配置
    LOGGING_CONFIG["formatters"]["default"]["fmt"] = "%(asctime)s - %(levelname)s - %(message)s"
    LOGGING_CONFIG["formatters"]["default"]["datefmt"] = "%Y-%m-%d %H:%M:%S"
    LOGGING_CONFIG["formatters"]["access"][
        "fmt"
    ] = '%(asctime)s - %(levelname)s - %(client_addr)s - "%(request_line)s" %(status_code)s'
    LOGGING_CONFIG["formatters"]["access"]["datefmt"] = "%Y-%m-%d %H:%M:%S"

    # 根据环境调整配置
    if args.env == "pro":
        print("⚠️  生产环境已自动关闭热重载")
    
    try:
        # 设置环境变量，确保热重载时也能正确传递
        os.environ["ENV"] = args.env
        
        uvicorn.run(
            "app:app", 
            host=args.host, 
            port=args.port, 
            reload=enable_reload,
            reload_dirs=["app"] if enable_reload else None,  # 限制热重载目录
            reload_excludes=["migrations/*", "*.pyc", "__pycache__/*"] if enable_reload else None,  # 排除不需要重载的文件
            log_config=LOGGING_CONFIG,
            access_log=True
        )
    except KeyboardInterrupt:
        print("\n👋 服务器已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
